package com.presto.directo.mvvm.view

import android.content.Intent
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import com.presto.directo.R
import com.presto.directo.base.BaseFragment
import com.presto.directo.databinding.FragmentMainBinding
import com.presto.directo.mvvm.viewmodel.*
import com.presto.directo.utils.*

class MainFragment : BaseFragment() {

    private val binding by lazy { FragmentMainBinding.inflate(layoutInflater) }
    private val viewModel by lazy { getViewModel<MainFragmentViewModel>() }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (!UserUtil.isLogin()) {
            showFragment(LoanFragment.createFragment())
        }
        viewModel.statusLiveData.observe(viewLifecycleOwner) {
            when (it.loan_status) {
                "", "1" -> showFragment(LoanFragment.createFragment())
                "2" -> showFragment(LoadingFragment.createFragment(it))
                "3", "4" -> showFragment(RepayFragment.createFragment(it))
                "5" -> showFragment(FailFragment.createFragment())
            }
        }
        viewModel.errorLiveData.observe(viewLifecycleOwner) {
            SPUtil.putObject(UserUtil.USER, null)
            showFragment(LoanFragment.createFragment())
            startActivity(Intent(mActivity, LoginPhoneActivity::class.java))
        }
    }

    override fun onResume() {
        super.onResume()
        if (!UserUtil.isLogin()) return
        viewModel.getStatus()
    }

    private fun showFragment(fragment: Fragment) {
        childFragmentManager.beginTransaction().replace(R.id.content, fragment).commit()
    }

}